<?php
/**
 * Created by Stefan Ho.
 * User: Stefan <xiugang.he@skyee360.com>
 * Date: 2021-07-02 08:54
 */

define('TIME_ZONE', 'Asia/Shanghai');
define('DS', DIRECTORY_SEPARATOR);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
@set_time_limit(0);
define('ROOT_PATH', dirname(__FILE__) . DS);
date_default_timezone_set(TIME_ZONE);
define('TIMESTAMP', time());
require_once ROOT_PATH . './include/function.php';
if(function_exists('mysql_connect')) {
    require ROOT_PATH . './include/db_mysql.php';
} else {
    require ROOT_PATH . './include/db_mysqli.php';
}
$argv = array_value($_SERVER, 'argv');
$mod = $argv[1] ?? '';
$mod_array = ['index', 'test'];
$mod = !in_array($mod, $mod_array) ? 'index' : $mod;
/** db */
$_config = [];
$config_file = ROOT_PATH . './config.php';
if(!file_exists($config_file)) {
    exit('config err');
} else {
    include $config_file;
}
$dbhost = $_config['db'][1]['dbhost'];
$dbname = $_config['db'][1]['dbname'];
$dbpw = $_config['db'][1]['dbpw'];
$dbuser = $_config['db'][1]['dbuser'];
$dbcharset = $_config['db'][1]['dbcharset'];
$tablepre = $_config['db'][1]['tablepre'];
$db = new dbstuff();
$db->connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset);
/**
 * 主函数
 */
function run_index() {
    global $db, $tablepre, $_config;
    $mail_config = $_config['mail_server'];
    $today = date('m-d', TIMESTAMP);
    $user_list = $db->fetch_all("SELECT * FROM {$tablepre}user WHERE DATE_FORMAT(job_time, '%m-%d')='" . $today . "'");
    if(empty($user_list)) {
        echo 'No data' . PHP_EOL;
        exit;
    }
    foreach($user_list as $item) {
        $res = send_mail($mail_config, $item['email'], $mail_config['title'], $mail_config['content']);
        pr('send ' . $item['email'], $res);
        echo PHP_EOL;
    }
}

/**
 * 测试邮件
 */
function run_test() {
    global $_config;
    $mail_config = $_config['mail_server'];
    $to = $mail_config['admin'];
    if(!$to) {
        echo 'No email' . PHP_EOL;
        exit;
    }
    $mail_config['admin'] = '';
    $res = send_mail($mail_config, $to, $mail_config['title'], $mail_config['content']);
    pr($res);
}

$run = 'run_' . $mod;
$run();
